#include "stateMachine.h"
#include <stdlib.h>
StateOutcome stateChange(void* me, StateHandler newState, TransitionAction nextAction);
const Event initEvent={INIT_CODE,0};

const Event exitEvent={EXIT_CODE,0};

const Event entryEvent={ENTRY_CODE,0};

inline StateOutcome stateChange(void* me, StateHandler newState, TransitionAction nextAction){
	StateMachine* temp = (StateMachine*)me;
	temp->state = newState;
	temp->passageAction=nextAction;
	return EVENT_CHANGED;
}
void stateMachineOnInit(void* me,StateHandler initState){
	stateChange(me,initState,NULL);
	stateMachineDispatcher(me,&initEvent);
}
void stateMachineDispatcher(void* me,const  Event* e){
	StateOutcome outcome;
	StateMachine* temp = (StateMachine*)me;
	StateHandler previousState=temp->state;
	outcome=temp->state(me,e);
	if ((outcome==EVENT_HANDLED)||(outcome==EVENT_IGNORED))
		return;
	else
	{
		previousState(me,&exitEvent);
		if(temp->passageAction!=NULL)
			temp->passageAction(me);
		temp->state(me,&entryEvent);
	}
}
void stateMachineOnInit2(void* me,StateHandler initState,Event* e){
	stateChange(me,initState,NULL);
	stateMachineDispatcher(me,e);
}
